package boxiapp

import(
	"fmt"
	"net/http"
	"appengine"
	"appengine/urlfetch"
	"io/ioutil"
	"bytes"
	"regexp"
)

func init(){
	http.HandleFunc("/", handler)
	http.HandleFunc("/f/", handleArticle)
}

func handler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	client := urlfetch.Client(c)
	resp, err := client.Get(r.URL.RawQuery)
	if err != nil {
		http.Error(w, r.URL.RawQuery, http.StatusInternalServerError)
		return
	}

	//fmt.Fprintf(w, r.URL.RawQuery)
	msg, _:= ioutil.ReadAll(resp.Body)
	content := bytes.NewBuffer(msg).String()
	fmt.Fprintf(w, content)
}

func handleArticle(w http.ResponseWriter, r *http.Request){
	c := appengine.NewContext(r)
	client:=urlfetch.Client(c)
	resp,_ := client.Get(r.URL.RawQuery)

	msg,_:=ioutil.ReadAll(resp.Body)
	reg,_ := regexp.Compile("<.*?>.*</.*?>")

	content := bytes.NewBuffer(msg).String()
	ps := reg.FindAllString(content,100)
	for i := 0; i < len(ps); i++{
		fmt.Fprintf(w, ps[i])
		fmt.Fprintf(w, "\n")
	}
}
